package com.ocean.security;

import com.ocean.core.util.StringUtil;
import com.ocean.security.filter.CustomOncePerRequestFilter;
import com.ocean.security.handler.RestAccessDeniedHandler;
import com.ocean.security.handler.RestAuthenticationEntryPoint;
import com.ocean.security.properties.MatchersProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * Security主配置
 *
 * @author zhang
 * @since 2021/9/10
 */
@Order(100)
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfigurer {

    @Autowired
    private MatchersProperties matchersProperties;

    @Autowired
    private AuthenticationConfiguration authenticationConfiguration;

    @Autowired
    private CustomOncePerRequestFilter customOncePerRequestFilter;

    public static List<String> MATCHERS = new ArrayList<String>() {{
        add("/v3/api-docs/**");
        add("/doc.html");
        add("/webjars/**");
    }};

    /**
     * 密码加密规则
     *
     * @return BCryptPasswordEncoder
     */
    @Bean
    public static PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(MATCHERS.toArray(new String[0]))
                .permitAll()
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated();

        http.exceptionHandling()
                .authenticationEntryPoint(new RestAuthenticationEntryPoint())
                .accessDeniedHandler(new RestAccessDeniedHandler())
        ;

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.formLogin();

        http.addFilterBefore(customOncePerRequestFilter, UsernamePasswordAuthenticationFilter.class);

        http.csrf().disable();

        return http.build();
    }

    /**
     * 放行所有options请求
     */
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
    }

    @PostConstruct
    public void init() {
        List<String> allow = matchersProperties.getAllow();
        if (StringUtil.isNotNull(allow)) {
            MATCHERS.addAll(allow);
        }
    }

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
}